package com.wehealth.three.lib_common.utils

import android.app.Application
import android.content.Context
import android.content.SharedPreferences


/***
 * @author 栾桂明
 * @date 2021年4月15日
 * @desc SharePreference工具类
 */
object SPUtil {
    private const val CACHE_FILE = "cache_file"
    fun putString(key: String, value: String?) {
        val shared = getShared()

        shared?.edit()?.putString(key, value)?.commit()
    }

    fun getString(key: String): String? {
        val shared = getShared()
        if (shared != null) {
            return shared.getString(key, null)
        }
        return null
    }


    fun putBoolean(key: String, value: Boolean) {
        val shared = getShared()
        shared?.edit()?.putBoolean(key, value)?.commit()
    }

    fun getBoolean(key: String, defaultValue: Boolean): Boolean {
        val shared = getShared()
        if (shared != null) {
            return shared.getBoolean(key, defaultValue)
        }
        return false
    }


    fun putInt(key: String, value: Int) {
        val shared = getShared()
        shared?.edit()?.putInt(key, value)?.commit()
    }

    fun putLong(key: String, value: Long) {
        val shared = getShared()
        shared?.edit()?.putLong(key, value)?.commit()
    }

    fun getInt(key: String, defaultValue: Int): Int {
        val shared = getShared()
        if (shared != null) {
            return shared.getInt(key, defaultValue)
        }
        return 0
    }

    fun getLong(key: String, defaultValue: Long): Long {
        val shared = getShared()
        if (shared != null) {
            return shared.getLong(key, defaultValue)
        }
        return 0
    }


    private fun getShared(): SharedPreferences? {
        val application: Application? = AppGlobals.get()
        if (application != null) {
            return application.getSharedPreferences(CACHE_FILE, Context.MODE_PRIVATE)
        }
        return null
    }

    fun setPreferenceListener(preferenceChangeListener: SharedPreferences.OnSharedPreferenceChangeListener) {
        getShared()?.registerOnSharedPreferenceChangeListener(preferenceChangeListener)
    }

}